<template>
  <view class="page pageBg-color">

    <view class="search-bar">
      <uni-search-bar @confirm="onSearch" @cancel="onClear" @clear="onClear" v-model="searchKeyword" focus
        placeholder="搜索">
      </uni-search-bar>
    </view>

    <view v-show="dataList.length <= 0 && isEmpty" class="search-keywords">

      <view class="history">
        <view class="topTitle">
          <view class="text">
            <text>最近搜索</text>
          </view>
          <view class="delete">
            <view @click="onRemoveHistory('all')" v-show="isDelete" class="all">
              <text>全部删除</text>
            </view>
            <view v-show="isDelete" class="center">
              <text>|</text>
            </view>
            <view @click="onRemoveHistory('cancel')" v-show="isDelete" class="Cancel">
              <text>完成</text>
            </view>
            <view @click="onRemoveHistory('icon')" v-show="!isDelete" class="icon">
              <uni-icons type="trash" size="25"></uni-icons>
            </view>
          </view>
        </view>
        <view class="tabs">
          <view v-if="historySearch.length > 0" v-for="tab in historySearch" :key="tab?.timestamp"
            @click="clickTab(tab?.keyword)" class="tab">
            <text>{{ tab?.keyword }}</text>
            <view v-show="isDelete" class="del-icon">
              <uni-icons type="closeempty" size="15"></uni-icons>
            </view>
          </view>
          <view v-else class="tab">
            <text>暂无搜索历史</text>
          </view>
        </view>
      </view>

      <view class="recommend">
        <view class="topTitle">
          <view class="text">
            <text>热门搜索</text>
          </view>
        </view>
        <view class="tabs">
          <view class="tab" v-for="tab in recommendList" :key="tab" @click="clickTab(tab, 'hot')">
            <text>{{ tab }}</text>
          </view>
        </view>
      </view>

    </view>

    <view class="dataList">
      <com-empty v-if="isSearch && (isEmpty && !isLoading)"></com-empty>
      <view v-else>
        <view class="content">
          <view @click="goPreview(item._id)" v-for="item in dataList" :key="item._id" class="item">
            <image class="image" :src="item.smallPicurl" mode="aspectFill" lazy-load />
          </view>
        </view>
        <com-loadFooter :isHasMore="isHasMore" :isLoading="isLoading"></com-loadFooter>
      </view>
    </view>

    <com-backTop :fixed="fixed"></com-backTop>

  </view>
</template>


<script lang="ts" setup>
import { ref } from 'vue';
import { onPullDownRefresh, onReachBottom, onPageScroll } from '@dcloudio/uni-app';
import { API } from "@/services/api";
import { isEmpty as isEmptyFn } from '@/utils/utils';
import { useSearchHistoryStore, useClassListStore } from "@/store";
const SearchHistoryStore = useSearchHistoryStore();
const ClassListStore = useClassListStore();

const searchKeyword = ref(""); // 搜索关键词
const historySearch = ref(SearchHistoryStore.uniqueKeywords || []); // 搜索历史词
const recommendList = ref(["美女", "帅哥", "宠物", "卡通"]); // 热门搜索词
const isSearch = ref(false); // 搜索状态，第一次或取消搜索的时候不显示暂无数据
const isDelete = ref(false); // 删除历史记录功能的状态

const dataList: any = ref([]); // 数据列表
const page = ref(1); // 页码
const isLoading = ref(false); // 加载状态
const isHasMore = ref(false); // 是否有更多数据可加载
const isEmpty = ref(true); // 数据是否为空

const fixed = ref(false); // 刷新、返回顶部 按钮的显示

// 监听用户下拉动作
onPullDownRefresh(() => {
  onRefresh();
});

// 页面滚动到底部的事件
onReachBottom(() => {
  if (isHasMore.value) {
    getData();
  }
});

// 监听页面滚动
onPageScroll((e) => {
  fixed.value = e.scrollTop > 200;
});

// 用户下拉执行需要执行的函数
const onRefresh = () => {
  if (isEmptyKeyWord()) return;
  dataList.value = [];
  page.value = 1;
  getData();
};

// 输入框的关键词是否为空
const isEmptyKeyWord = () => {
  let KeyWord = searchKeyword.value.trim();
  if (isEmptyFn(KeyWord)) {
    searchKeyword.value = "";
    uni.stopPullDownRefresh();
    uni.showToast({ title: "搜索词不能为空", icon: "error" });
    return true;
  }
  return false;
};

// 添加搜索记录
const pushHistory = () => {
  if (isEmptyKeyWord()) return;
  SearchHistoryStore.addHistory(searchKeyword.value);
  historySearch.value = SearchHistoryStore.uniqueKeywords;
};

// 输入框 确认 事件
const onSearch = () => {

  // 添加历史数据到数组并快速去重（未持久化）
  // historySearch.value.unshift(searchKeyword.value);
  // historySearch.value = [...new Set(historySearch.value)];
  // 另一种方法
  // historySearch.value = [...new Set([searchKeyword.value, ...historySearch.value])];
  isSearch.value = true;
  pushHistory();
  onRefresh();
};

// 点击 取消、清除 按钮时触发事件
const onClear = () => {
  searchKeyword.value = "";
  isSearch.value = false;
  dataList.value = [];
  page.value = 1;
  isLoading.value = false;
  isHasMore.value = true;
  isEmpty.value = true;
};

// 删除历史记录
const onRemoveHistory = (type: string) => {
  if (type === "icon" || type === "cancel") {
    isDelete.value = !isDelete.value;
  } else if (type === "all") {
    if (SearchHistoryStore.historyCount === 0) {
      uni.showToast({ title: "没有可删除的记录", icon: "none" });
      return;
    }
    uni.showModal({
      title: "是否清空历史搜索？",
      success: res => {
        if (res.confirm) {
          SearchHistoryStore.clearAllHistory();
          historySearch.value = SearchHistoryStore.uniqueKeywords;
          isDelete.value = false;
          uni.showToast({ title: "历史记录已删除", icon: "none" });
        }
      }
    })
  }
};

// 点击标签进行搜索
const clickTab = (value: string, type?: string) => {
  if (isDelete.value && type != "hot") {
    SearchHistoryStore.removeHistory(value);
    historySearch.value = SearchHistoryStore.uniqueKeywords;
  } else {
    searchKeyword.value = value;
    onSearch();
  }
};

// 获取接口的数据
const getData = () => {
  isLoading.value = true;
  API.searchWall(searchKeyword.value.trim(), page.value, 12)
    .then((res: any) => {
      console.log(`~~~获取 page = ${page.value} 的数据`);
      let newList = [...dataList.value];
      if (page.value === 1) newList = [];
      dataList.value = newList.concat(res.data || []);
      isLoading.value = false;
      isHasMore.value = res.data && res.data.length >= 12;
      isEmpty.value = dataList.value.length <= 0;
      page.value++;
      ClassListStore.setList(dataList.value);
    })
    .catch(() => {
      isLoading.value = false;
      isHasMore.value = false;
      isEmpty.value = true;
    })
};

// 去到预览页面
const goPreview = (id: string) => {
  uni.navigateTo({
    url: `/pages/pkgB/typePreview/index?id=${id}`
  })
};

</script>


<style lang="scss" scoped>
@use "style.scss";
</style>